﻿using System;
using System.Configuration;
using mojoPortal.Net;
using mojoPortal.Web;
using Resources;
using mojoPortal.Web.Framework;
using System.Collections;
using mojoPortal.Business;
using ud_gSDMS.Code_Service;
using mojoPortal.Business.WebHelpers;
using System.Linq;
using System.Data;
using Telerik.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Web.UI;
using Brettle.Web.NeatUpload;


namespace ud_gSDMS.Testing
{
    public partial class Close_Error : mojoBasePage
    {
        private int pageID = -1;
        private int id = -1;
        private int error = -1;
        private SiteUser _siteUser;
        protected String cacheDependencyKey;

        void Page_Load(object sender, EventArgs e)
        {
            try
            {
                _siteUser = SiteUtils.GetCurrentSiteUser();

                //SiteUser.ConfirmRegistration()
                if (_siteUser == null)
                {
                    WebUtils.SetupRedirect(this, SiteRoot + "/AccessDenied.aspx");
                }
                else
                {
                    if (gSDMS_BL.mp_User_IsRole(_siteUser.UserId, "3|1") == false)
                    {
                        WebUtils.SetupRedirect(this, SiteRoot + "/AccessDenied.aspx");
                    }
                }

                //if (!UserCanEditPage() || !UserCanViewPage())
                //{
                //    WebUtils.SetupRedirect(this, SiteRoot + "/AccessDenied.aspx");
                //}
                if (!Page.IsPostBack)
                {
                    PopulateLabels();
                    PopulateControls();
                }

                
            }
            catch
            {
            }
        }
        private void PopulateLabels()
        {

        }
        private void PopulateControls()
        {
            LoadSetting();
            LoadControl();
        }

        

        #region event
       
        void btnSend_Click(object sender, EventArgs e)
        {
       
            try
            {
                // File_Attach_ID == 0
                if (cboStatus.SelectedItem.ToString() == "Open")
                    gSDMS_BL.ud_gSDMS_CAT_PROJECT_TEST_ERROR_Clo(error, edContent.Text, int.Parse(cboStatus.SelectedValue));
                else
                    gSDMS_BL.ud_gSDMS_CAT_PROJECT_TEST_ERROR_Clo(error, int.Parse(cboStatus.SelectedValue));

                if (chkSendEmail.Checked == true)
                {
                    int _id = id;
                    var userManager = gSDMS_BL.mp_User_get(cboSender.SelectedValue, null);
                    var assigned = gSDMS_BL.mp_User_get(cboAssign_To.SelectedValue, null);
                    var status = cboStatus.SelectedItem.ToString() == "Closed" ? "CLOSED" : "REOPENED";
                    var cc = gSDMS_BL.ud_gSDMS_PROJECT_TEST_Get(id);

                    var emailFrom = userManager.Email;
                    var emailCc = cc.ud_gSDMS_PROJECT.mp_User.Email;
                    var emailTo = assigned.Email;

                    var subject = string.Format("[gSDMS-TESTING] {0} ERROR IN PROJECT : {1} FROM gSDMS", status, lbProject_Code.Text);
                    var textBody =
                                    "Dear " + assigned.LoginName + "<br/><br/> Error has been " + status.ToLower() + " in project: <b>" + lbProject_Code.Text + "</b>. <br/><br/> <b><u>Error Code</b></u> : " + lbError_Code.Text + "<br/><br/> <b><u>Title</b></u> : " + txtTitle.Text +
                        "<br/><br/> Please enter follow link to check: " + SiteRoot + "/gsdmsmodule/Testing/Error_Lists.aspx?pageid=9&id=" + id + " <br/><br/> <b><u>Feedback Note</b></u> : " + edFeedback_Notes.Text + "<br/><br/> Regard, <br/>" + userManager.LoginName;    
                    var siteGuid = siteSettings.SiteGuid;
                    Library.SendMail(emailFrom, emailTo, emailCc, string.Empty, subject, textBody, siteGuid);
                    chkSendEmail.Checked = false;
                }
            }
            catch (Exception ex)
            {
            }
            WebUtils.SetupRedirect(this, SiteRoot + "/gsdmsmodule/testing/Error_Lists.aspx?pageid=9&testid=" + id);

        }

        void rptAttachments_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            var path = Request.PhysicalApplicationPath + "Data/gSDMSAttachments/" + e.CommandArgument;
            path = path.Replace("/", "\\");
            switch (e.CommandName)
            {
                case "DeleteItem":
                    var repository = new ud_gSDMS_Attachments();
                    bool a = repository.DeleteItemAttachment(e.CommandArgument.ToString());
                    bool b = repository.Delete(e.CommandArgument.ToString());
                    if (a && b)
                    {
                        if (File.Exists(path))
                        {
                            File.Delete(path);
                        }
                    }
                    break;
                case "DownloadItem":
                    {
                        var repository_ = new ud_gSDMS_Attachments();
                        var file = repository_.GetOne(Convert.ToInt32(e.CommandArgument));
                        path = Request.PhysicalApplicationPath + "Data/gSDMSAttachments/" + file.ServerFileName;

                        FileInfo f = new FileInfo(path);

                        if (f.Exists)
                        {

                            Response.Clear();
                            Response.ContentType = "application/octet-stream";
                            Response.AddHeader("Content-Disposition", "attachment; filename=" + Library.RemoveSign4VietnameseString(file.FileName).Replace(" ", "-"));
                            Response.WriteFile(path);
                            Response.End();
                            //if file does not exist
                        }
                        else
                        {
                            Response.Write("This file does not exist.");
                        }
                        break;
                    }

            }
            WebUtils.SetupRedirect(this, Request.RawUrl);
        }

        void rptAttachments_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            Image imgType = (Image)e.Item.FindControl("imgType");
            if (imgType == null) return;
            string name = DataBinder.Eval(e.Item.DataItem, "p.FileName", "{0}").Trim();
            // ReSharper disable PossibleNullReferenceException
            var imgFile = Path.GetExtension(name).ToLower().Replace(".", "") + ".png";
            var path = Request.PhysicalApplicationPath + "/Data/SiteImages/Icons/" + imgFile;
            if (File.Exists(path))
            {
                imgType.ImageUrl = ImageSiteRoot + "/Data/SiteImages/Icons/" + imgFile;
            }
            var ibtnDelete = (ImageButton)e.Item.FindControl("ibtnDelete");
            ud_Utilities.Utilities.AddConfirmButton(ibtnDelete, "Do you want to delete this file?");
        }

        void btnUpload_Click(object sender, EventArgs e)
        {
            var upLoadPath = Page.Server.MapPath(WebUtils.GetApplicationRoot() + "/Data/gSDMSAttachments/");
            if (!Directory.Exists(upLoadPath))
            {
                Directory.CreateDirectory(upLoadPath);
            }
            if (hidId.Value == "")
            {
                return;
            }
            //if (article == null) { WebUtils.SetupRedirect(this, Request.RawUrl); return; }
            //if ((article.ItemId <= 0) || (article.ModuleId != moduleId)) { WebUtils.SetupRedirect(this, Request.RawUrl); return; }
            if (file1.HasFile && file1.FileName != null && file1.FileName.Trim().Length > 0)
            {
                var repository = new ud_gSDMS_Attachments();

                string serverFileName = Guid.NewGuid() + ".config";
                int fileID;


                var suss = repository.Create(file1.FileName, serverFileName, (int)(file1.ContentLength / 1024), out fileID, OptionForm.Testing.ToString(), hidId.Value);
                if (suss)
                {
                    var destPath = upLoadPath + serverFileName;

                    if (File.Exists(destPath))
                    {
                        File.Delete(destPath);

                    }
                    file1.MoveTo(destPath, MoveToOptions.Overwrite);
                }
                BindAttachments();
            }

            CacheHelper.TouchCacheDependencyFile(cacheDependencyKey);
            //WebUtils.SetupRedirect(this, SiteRoot + article.ItemUrl.Replace("~/", "/"));
        }

        #endregion event

        #region OnInit

        protected override void OnPreInit(EventArgs e)
        {
            AllowSkinOverride = true;
            base.OnPreInit(e);
            Load += Page_Load;
        }


        protected override void OnInit(EventArgs e)
        {
            LoadParams();
            LoadPanels();
            base.OnInit(e);

            rptAttachments.ItemDataBound += rptAttachments_ItemDataBound;
            rptAttachments.ItemCommand += rptAttachments_ItemCommand;
            btnUpload.Click += btnUpload_Click;
            btnSend.Click += new EventHandler(btnSend_Click);
            SiteUtils.SetupEditor(edFeedback_Notes);
            SiteUtils.SetupEditor(edContent);
            SuppressPageMenu();
        }

        private void LoadControl()
        {
            if (id != -1)
            {
                hidId.Value = error.ToString();
                //gen ERROR_CODE
                var status = gSDMS_BL.ud_gSDMS_CAT_ERROR_STATUS_Get("Open", "Closed");

                cboStatus.DataValueField = "CAT_Error_Status_ID";
                cboStatus.DataTextField = "Name";
                cboStatus.DataSource = status;
                cboStatus.DataBind();
                

                var users = gSDMS_BL.mp_User_Lst("3");
                cboSender.DataValueField = "UserID";
                cboSender.DataTextField = "LoginName";
                cboSender.DataSource = users;
                cboSender.DataBind();
                cboSender.SelectedValue = _siteUser.UserId.ToString();

                var projectTest = gSDMS_BL.ud_gSDMS_PROJECT_TEST_Get(id);
                var assign = gSDMS_BL.getMemberList(projectTest.ud_gSDMS_PROJECT.Project_ID.ToString());
                cboAssign_To.DataValueField = "UserID";
                cboAssign_To.DataTextField = "LoginName";
                cboAssign_To.DataSource = assign;
                cboAssign_To.DataBind();
                cboAssign_To.SelectedValue = projectTest.ud_gSDMS_PROJECT.Project_Leader.ToString();

                var temp = gSDMS_BL.ud_gSDMS_PROJECT_TEST_ERROR_Get(error);
                if (temp.Rows.Count > 0)
                {

                    lbProject_Code.Text = temp.Rows[0].ItemArray[3].ToString();
                    lbError_Code.Text = temp.Rows[0].ItemArray[1].ToString();
                    txtTitle.Text = temp.Rows[0].ItemArray[4].ToString();
                    edFeedback_Notes.Text = temp.Rows[0].ItemArray[5].ToString();
                    edContent.Text = temp.Rows[0].ItemArray[6].ToString();
                    lbCreate_Date.Text = ((DateTime)temp.Rows[0].ItemArray[9]).ToLongDateString();
                    cboStatus.SelectedValue = temp.Rows[0].ItemArray[11].ToString();
                    //cboAssign_To.SelectedValue = temp.Rows[0].ItemArray[7].ToString();

                }

                BindAttachments();
                
            }

        }

        private void LoadSetting()
        {
            edContent.WebEditor.ToolBar = mojoPortal.Web.Editor.ToolBar.SimpleWithSource;
            edContent.WebEditor.Height = 200;
            edFeedback_Notes.WebEditor.ToolBar = mojoPortal.Web.Editor.ToolBar.Full;
            edFeedback_Notes.WebEditor.Height = 200;
            
        }

        private void LoadParams()
        {

            pageID = WebUtils.ParseInt32FromQueryString("pageid", pageID);
            id = WebUtils.ParseInt32FromQueryString("testid", true, id);
            error = WebUtils.ParseInt32FromQueryString("error", true, error);

        }

        private void LoadPanels()
        {
            bool showLeftColumnAdmin = ConfigHelper.GetBoolProperty("ShowLeftColumnAdmin", false);
            bool showRightColumnAdmin = ConfigHelper.GetBoolProperty("ShowRightColumnAdmin", false);
            bool showTopColumnAdmin = ConfigHelper.GetBoolProperty("ShowTopColumnAdmin", false);
            bool showBottomColumnAdmin = ConfigHelper.GetBoolProperty("ShowBottomColumnAdmin", false);
            int showCenterColumnAdmin = ConfigHelper.GetIntProperty("ShowCenterColumnAdmin", 0);
            LoadSideContent(showLeftColumnAdmin, showRightColumnAdmin, showTopColumnAdmin, showBottomColumnAdmin, showCenterColumnAdmin);
        }

        private void BindAttachments()
        {
            var repository = new ud_gSDMS_Attachments();
            var item = repository.GetByItemID(OptionForm.Testing.ToString(), error.ToString());
            rptAttachments.DataSource = item;
            rptAttachments.DataBind();

            lblAttachments.Visible = rptAttachments.Items.Count > 0;
        }
        #endregion
    }
}